import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';
import {Link} from 'react-router-dom';
import {baseDataStatus, currency} from '../Enum';
import {conventEnumValueToString, formatAmount} from '../utils';
import {PERMISSION, hasPermissions} from './constants';
import {abandonOrder} from './api';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {injectIntl, formatMessage} from './intl';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.data.find(d => d.id === id);
        abandonOrder(id, record.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }

    render() {
        const {pageIndex, pageSize, total, sortedColumnKey,
            sortedOrder, permissions, data, errorMessage, loading} = this.props;
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table className="white-space-nowrap"
                    dataSource={data}
                    rowKey="id"
                    pagination={pagination}
                    loading={loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE} >
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.brandCode',
                        defaultMessage: '品牌'
                    })}
                    dataIndex="brandCode"
                    sorter="true"
                    sortOrder={sortedColumnKey === 'brandCode' && sortedOrder}>
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.code',
                        defaultMessage: '编号'
                    })}
                    dataIndex="code"
                    sorter="true"
                    sortOrder={sortedColumnKey === 'code' && sortedOrder}>
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.dealerCode',
                        defaultMessage: '总代编号'
                    })}
                    dataIndex="dealerCode">
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.year',
                        defaultMessage: '年份'
                    })}
                    dataIndex="year">
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.amount',
                        defaultMessage: '总预算'
                    })}
                    dataIndex="amount"
                    render={text => formatAmount(text)}>
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.currency',
                        defaultMessage: '币种'
                    })}
                    dataIndex="currency"
                    render={text => conventEnumValueToString(currency, text)}>
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.text.status',
                        defaultMessage: '状态'
                    })}
                    dataIndex="status"
                    render={text => conventEnumValueToString(baseDataStatus, text)}>
                    </Table.Column>
                    <Table.Column title={formatMessage({
                        id: 'tablePanel.btn.done',
                        defaultMessage: '操作'
                    })}
                    dataIndex="operate"
                    fixed="right"
                    width={FIXED_COLUMN_WIDTH}
                    render={(t, r) => {
                        const menus = [
                            {
                                id: PERMISSION.update,
                                children: <Link key="update" to={routes.update.format(r.id)}>{formatMessage({
                                    id: 'tablePanel.btn.edit',
                                    defaultMessage: '编辑'
                                })}</Link>,
                                hidden: !(hasPermissions(permissions, PERMISSION.update) &&
                                    hasPermissions(r.options, PERMISSION.update)),
                            },
                            {
                                id: PERMISSION.abandon,
                                children: ref =>
                                    <WrappedPopconfirm
                                        key="abandon"
                                        placement="topLeft"
                                        onConfirm={this.onClickAbandonBtn}
                                        onVisibleChange={ref.setMenuVisible}
                                        id={r.id}
                                        title={formatMessage({
                                            id: 'tablePanel.btn.isabandon',
                                            defaultMessage: '是否确认作废？'
                                        })}>
                                        <a key="abandon">{formatMessage({
                                            id: 'tablePanel.btn.abandon',
                                            defaultMessage: '作废'
                                        })}</a>
                                    </WrappedPopconfirm>,
                                hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                            }
                        ];
                        return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                    }}>
                    </Table.Column>
                </Table>
            </div>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));

